(function($){
    $.fn.serializeJson=function(){
        var serializeObj={};
        var array=this.serializeArray();
        // var str=this.serialize();
        $(array).each(function(){
            if(serializeObj[this.name]){
                if($.isArray(serializeObj[this.name])){
                    serializeObj[this.name].push(this.value);
                }else{
                    serializeObj[this.name]=[serializeObj[this.name],this.value];
                }
            }else{
                serializeObj[this.name]=this.value;
            }
        });
        return serializeObj;
    };
})(jQuery);

var tagActivity,tagDay;
var icons = {
    1 : ' fa-plane btn-warning ',
    2 : ' fa-cutlery btn-pink ',
    3 : ' fa-camera btn-inverse ',
    4 : ' fa fa-bed btn-pink '
    };
var remarkEditor,introductionEditor,ueditor;
$(document).ready(function(){
    var timeLineFn = baidu.template('timeLineTmpl');
    baidu.template.ESCAPE = false;
    var activityFn = baidu.template('activityTmpl');
    /*$("#typeId").select2({
        width:'element'
    });*/
    $('select').chosen({allow_single_deselect:true,width: '100%',disable_search:true});
    remarkEditor = UE.getEditor('remarkEditor', {wordCount: true});
    introductionEditor = UE.getEditor('introductionEditor', {wordCount: true});

    ueditor = UE.getEditor('ueditor', {wordCount: true,zIndex:1200,scaleEnabled:true});

    $('body').on('click', '.add-day', function(e) {
        e.preventDefault();
        $('#iDayTitle').val('');
        $('#dayModalTitle').text('添加日行程');
        $('#dayModal').modal('show');
        tagDay=null;
    });
    $('body').on('click', '.edit-day', function(e) {
        e.preventDefault();
        $('#dayModalTitle').text('修改日行程');
        tagDay=$(this).parents('div.timeline-label');
        $('#iDayTitle').val(tagDay.find('.day-title').text());
        $('#dayModal').modal('show');
    });
    $('#subDayBtn').click(function () {
        $('#dayModal').modal('hide');
        if(tagDay!=null && tagDay!='undefined'){
            tagDay.find('.day-title').text($('#iDayTitle').val());
        }else{
            $('#timeline_content').append(timeLineFn({
                dayNo:$('.timeline-container').length+1,
                dayTitle:$('#iDayTitle').val()
            }));
        }
    });

    $('body').on('click', '.add-activity', function() {
        $('#activityModalTitle').html('添加活动');
        tagActivity = null;
        tagDay = $(this).parents('div.timeline-container');
        $('#acTitle').val('');
        // $('#acType').val(1);
        setAcType(1);
        ueditor.setContent('');
        $('#activityModal').modal('show');
    });
    $('body').on('click', '.edit-activity', function(e) {
        e.preventDefault();
        tagActivity = $(this).parents('div.transparent');
        $('#acTitle').val(tagActivity.find('.activity-title').text());
        // $('#acType').val(tagActivity.find('[name="itype"]').val());
        setAcType(tagActivity.find('[name="itype"]').val());
        ueditor.setContent(tagActivity.find('.activity-content').html());
        $('#activityModal').modal('show');

    });
    $('#subAcBtn').click(function () {
        if(tagActivity!=null && tagActivity!='undefined'){
            tagActivity.find('.activity-title').text($('#acTitle').val());
            tagActivity.find('[name="itype"]').val($('#acType').val());
            tagActivity.find('.activity-content').html(ueditor.getContent());
            var activityType = tagActivity.parents('div.timeline-item').find('.activity-type');
            activityType.removeClass('fa-cutlery').removeClass('fa-plane').removeClass('fa-camera');
            activityType.removeClass('btn-warning').removeClass('btn-pink').removeClass('btn-inverse')
            activityType.addClass(icons[$('#acType').val()]);
        }else{
            tagDay.append(activityFn({
                title:$('#acTitle').val(),
                iType:$('#acType').val(),
                content:ueditor.getContent(),
                typeClass:icons[$('#acType').val()]
            }));
        }
        $('#activityModal').modal('hide');
    });

    $('body').on('click', '.delete-activity', function(e) {
        e.preventDefault();
        $(this).parents('div.timeline-items').remove();
    });
    $('body').on('click', '.delete-day', function(e) {
        e.preventDefault();
        $(this).parents('div.timeline-container').remove();
        $('.timeline-container').each(function(index,item){
            $(this).find('.day-no').text('第'+(index+1)+'天');
        });
    });

    $('#submitBtn').click(function (e) {
        bootbox.confirm({
            title:'确认信息',
            message: '确定要提交本线路信息？',
            buttons: {
                confirm: {
                    label: '确定',
                    className: 'btn-success'
                },
                cancel: {
                    label: '取消',
                    className: 'btn-default'
                }
            },
            callback: function (result) {
                if(result){
                    doSubmit();
                }
            }
        });
    });
    $('#resetBtn').click(function(e) {
        $('#routeForm')[0].reset();
    });
});

function doSubmit() {
    if (!$("#routeForm").valid()) {
        return;
    }
    var data=$("#routeForm").serializeJson();//表单序列化
    data.remark = remarkEditor.getContent();
    data.introduction = introductionEditor.getContent();
    data.trip = JSON.stringify(initParam());
    jQuery.ajax({
        dataType : 'json',
        type:'post',
        url : $('#routeForm').attr('action'),
        data :data,
        success : function(result) {
            if(result.code=='200'){
                window.location.href="/tour/route/list.do?taId="+$('#travelAgencyId').val();
            }else{
                bootbox.alert(result.message);
            }
        },
        error:function () {
            bootbox.alert('请求失败！');
        }
    });
}

function initParam(){
    var tripInfo = [];
    $.each($('.timeline-container'),function (index,iTrip) {
        var activities =[];
        $.each($(iTrip).find('.transparent'),function (acIndex,iActivity) {
            activities.push({
                sortNo : acIndex+1,
                typeId : $(iActivity).find('[name="itype"]').val(),
                title : $(iActivity).find('.activity-title').text(),
                content : $(iActivity).find('.activity-content').html()
            });
        });
        tripInfo.push({
            dayNo:index+1,
            title:$(iTrip).find('.day-title').text(),
            activities:activities
        });
    });
    return tripInfo;
}
function setAcType(value){
    $("#acType").html('<option value="1" '+(value==1?' selected="selected" ':'')+'>交通</option>\n' +
                        '<option value="2" '+(value==2?' selected="selected" ':'')+'>餐饮</option>\n' +
                        '<option value="3" '+(value==3?' selected="selected" ':'')+'>活动</option>\n +' +
                        '<option value="4" '+(value==4?' selected="selected" ':'')+'>住宿</option>\n');
    $("#acType").trigger("chosen:updated");
}

$("#distributionPrice").blur(function(){
    if (parseFloat($("#totalFee").val()) <= parseFloat($("#distributionPrice").val())) {
                 //console.log(parseFloat($("#totalFee").val()));
                 //console.log(parseFloat($("#distributionPrice").val()));
        alert("商品结算价不能大于等于直客价！");
        return $(this).val("");
    }
});
$("#totalFee").on("blur",function(){
    if (parseFloat($("#totalFee").val()) <= parseFloat($("#distributionPrice").val())) {
                 //console.log(parseFloat($("#totalFee").val()));
                 //console.log(parseFloat($("#distributionPrice").val()));
        alert("商品直客价不能小于等于结算价！");
        return $(this).val("");
    }
});

function uploadImage() {
    // 检测是否支持File API
    if (window.File && window.FileReader && window.FileList && window.Blob) {
        var file = $('#imgFile').prop("files")[0];
        var form_data = new FormData();
        form_data.append("file[]", file);
        $.ajax({
            type: "POST",
            url: "/file/uploadFile",
            dataType : "json",
            processData: false,  // 注意：让jQuery不要处理数据
            contentType: false,  // 注意：让jQuery不要设置contentType
            data: form_data
        }).success(function(msg) {
            $("#imageUrl").val(msg.datas);
            // $("#imgUrl").attr("src",msg.datas)
        }).fail(function(msg) {
            console.log(msg);
        });
    } else {
        alert('不支持');
    }
}
